package com.chixing.config;

import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

public class HotRedisCacheManager  extends RedisCacheManager{
    public HotRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * 重新创建缓存的方法
     * @param name
     * @param cacheConfig
     * @return
     */
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        //名称中存在#标记进行到期时间配置
        if (!name.isEmpty() && name.contains("#")) {
            String[] SPEL = name.split("#");
            //配置缓存到期时间
            int cycle = Integer.parseInt(SPEL[1]);
            //单位
            String type = SPEL[2];

            long time = 0;

            switch (type) {
                case "s"://秒
                    time = cycle;
                    break;
                case "m"://分
                    time = 60 * cycle;
                    break;
                case "h"://时
                    time = 60 * 60 * cycle;
                    break;
                case "d"://天
                    time = 24 * 60 * 60 * cycle;
                    break;
            }
            return super.createRedisCache(SPEL[0], cacheConfig.entryTtl(Duration.ofSeconds(time)));
        }
        return super.createRedisCache(name, cacheConfig);
    }


}
